package com.fingard.dsp.bank.directbank.alipay01;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IH5Order;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.text.StringHelper;
import com.fingard.text.XmlHelper;
import net.sf.json.JSONObject;

import java.util.HashMap;

public class ALIPAY01H5Order extends ALIPAY01Base implements IH5Order {
    @Override
    public RetAtsUnifiedOrder submitH5Order(ReqUnifiedOrder p_req) {
        RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
        retAts.rdSeq = p_req.rdSeq;

        try {
            logIsExist();

            HashMap<String, String> tmpRetMap = new HashMap<String, String>();

            ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "order");
            if (actItem == null) {
                actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
            }
            if (actItem != null) {
            	String signType = "RSA2";
            	boolean useSignType = getBankConfig().getValueAsBool("useSignType");
            	if (useSignType) {
            		signType = actItem.signType;
            	}

            	String serverURL = bankFront.serverURL;
            	boolean useAlonewapURL = getBankConfig().getValueAsBool("useAlonewapURL");
            	WriteBankLogLn("useAlonewapURL:" + useAlonewapURL);
            	if (useAlonewapURL) {
                    serverURL = bankFront.getUrl("aloneH5Submit");
                }
                WriteBankUrlLogLn(serverURL);
                AlipayClient alipayClient = new DefaultAlipayClient(serverURL, actItem.appId,
                        actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);

                JSONObject alipayJsonRequest = new JSONObject();
				alipayJsonRequest.put("out_trade_no", p_req.rdSeq);
				alipayJsonRequest.put("subject", XmlHelper.encode(p_req.description));
				alipayJsonRequest.put("total_amount", p_req.amount);
				alipayJsonRequest.put("body", XmlHelper.encode(p_req.attach));
				alipayJsonRequest.put("timeout_express", getValidTime(p_req.getValidTime()));
				alipayJsonRequest.put("product_code", "QUICK_WAP_WAY");
                if (StringHelper.hasAnyChar(p_req.alipayUid)&&StringHelper.hasAnyChar(p_req.paymentNo)) {
                    alipayJsonRequest.put("scene", "InsuranceCompanyCN");
                }
                String enable_pay_channels = getBankConfig().getValueAsString("enablePayChannels");
                if(!StringHelper.isNullOrEmpty(enable_pay_channels)){
                    alipayJsonRequest.put("enable_pay_channels", enable_pay_channels);
                }
				
				boolean isInsuranceFlag = false;
                StringBuilder insuranceMsg = new StringBuilder();
                if (StringHelper.hasAnyChar(p_req.insureAreaCode) &&StringHelper.hasAnyChar(p_req.sHTradeNo) || "1".equals(p_req.realNameType)) {
                		isInsuranceFlag = true;
                        insuranceMsg.append("\"{\\\"insuranceFlag\":\"T\"")
                                            .append(",\"insuranceType\":\"alipay_auto_ins\"")
                                            .append(",\"shTradeNo\":\"")
                                            .append(p_req.sHTradeNo)
                                            .append("\"")
                                            .append(",\"insureAreaCode\":\"")
                                            .append(p_req.insureAreaCode)
                                            .append("\"")
                                            .append("}\"");
                    JSONObject insuranceInfo = new JSONObject();
                    insuranceInfo.put("insurance_info", insuranceMsg.toString());
                    alipayJsonRequest.put("extend_params", insuranceInfo);
                } else  if(StringHelper.hasAnyChar(p_req.alipayUid)&&StringHelper.hasAnyChar(p_req.paymentNo) || "0".equals(p_req.realNameType)){
                		isInsuranceFlag = true;
                        //在insurance_info新增
                        //insurance_payment_no  保险公司缴费支付订单
                        //realname_certified_alipay_uid 支付宝用户id。
                        insuranceMsg.append("\"{\\\"insurance_payment_no\":\"")
                                            .append(p_req.paymentNo)
                                            .append("\"")
                                            .append(",\"realname_certified_alipay_uid\":\"")
                                            .append(p_req.alipayUid)
                                            .append("\"")
                                            .append("}\"");
                    JSONObject insuranceInfo = new JSONObject();
                    insuranceInfo.put("insurance_info", insuranceMsg.toString());
                    alipayJsonRequest.put("extend_params", insuranceInfo);
                }

                String authFlag = "F";
				if ("1".equals(p_req.realNameFlag)) {
					authFlag = "T";
				} else if ("0".equals(p_req.realNameFlag)) {
					authFlag = "F";
				} else {
					if (StringHelper.hasAnyChar(p_req.oppActName) || StringHelper.hasAnyChar(p_req.certNumber) || StringHelper.hasAnyChar(p_req.cellPhone)) {
						authFlag = "T";
					}
				}
				
				JSONObject userInfoJson = new JSONObject();
				userInfoJson.put("name", p_req.oppActName);
				userInfoJson.put("mobile", p_req.cellPhone);
				userInfoJson.put("cert_type", convertCertTypeToBank(p_req.certType));
				userInfoJson.put("cert_no", p_req.certNumber);
				userInfoJson.put("need_check_info", authFlag);
				
				if ("T".equals(authFlag) && !isInsuranceFlag) {
					alipayJsonRequest.put("ext_user_info", userInfoJson);
				}
                
                AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
                if (p_req.needReturnURL) {
                    WriteBankLogLn2("returnURL:"+actItem.returnURL);
                    alipayRequest.setReturnUrl(actItem.returnURL);
                } else {
                    alipayRequest.setReturnUrl("");
                }
                WriteBankLogLn2("notifyURL:"+actItem.notifyURL);
                alipayRequest.setNotifyUrl(actItem.notifyURL);

                String bizContent = JSON.toJSONString(alipayJsonRequest);
				bizContent = bizContent.replaceAll("\\\\\\\\", "");
				alipayRequest.setBizContent(bizContent);
                
                WriteBankLogLn("发送银行的Bizcontent=" + alipayRequest.getBizContent());
                String result = alipayClient.pageExecute(alipayRequest).getBody();
                WriteBankLogStep3(result);

                if (result.length() > 0) {
                    tmpRetMap.put("Result", result);

                    retAts.respCode = "0";
                    retAts.respInfo = "签名成功";
                    retAts.customHashMap = tmpRetMap;
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "签名失败";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
    }

    @Override
    public RetAtsQueryOrder queryH5Pay(ReqQueryOrder p_req) {
        RetAtsQueryOrder retAts = new RetAtsQueryOrder();
        retAts.rdSeq = p_req.rdSeq;

        try {
            logIsExist();

            ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
            if (actItem != null) {
            	String signType = "RSA2";
            	boolean useSignType = getBankConfig().getValueAsBool("useSignType");
            	if (useSignType) {
            		signType = actItem.signType;
            	}
            	
                AlipayClient alipayClient = new DefaultAlipayClient(bankFront.serverURL, actItem.appId,
                        actItem.ownKeyStorePath, "json", getCharset(), actItem.oppCertFilePath, signType);

                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                request.setBizContent("{\"out_trade_no\":\"" + p_req.rdSeq + "\"}");

                WriteBankUrlLogLn(bankFront.serverURL);
                WriteBankLogStep2(request.getBizContent());

                AlipayTradeQueryResponse response = alipayClient.execute(request);
                WriteBankLogStep3(response.getBody());

                retAts.respCode = "0";
                retAts.respInfo = response.getMsg();
                if ("10000".equals(response.getCode())) {
                    retAts.transState = StringHelper.joinNotEmpty("+", response.getCode(), response.getTradeStatus());
                    retAts.payInfoCode = response.getTradeStatus();
                    retAts.outTransID = response.getTradeNo();
                    retAts.openId = response.getOpenId();
                    retAts.oppAct = response.getBuyerLogonId();
                } else {
                    retAts.transState = StringHelper.joinNotEmpty("+", response.getCode(), response.getSubCode());
                    retAts.payInfoCode = response.getSubCode();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respCode = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
    }
}
